#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <unistd.h>
#include <pthread.h>

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
void *Mastercode(void *args)
{
    char *name = static_cast<char *>(args);
    while (1)
    {
        usleep(100000);
        pthread_cond_signal(&gcond);
        std::cout << name << " 唤醒了一个线程 " << std::endl;
    }
    delete[] name;
}
void *Slavercode(void *args)
{
    char *name = static_cast<char *>(args);
    while (1)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex);
        std::cout << name << " 被唤醒 " << std::endl;
        pthread_mutex_unlock(&gmutex);
    }
    delete[] name;
}
void StartMaster(std::vector<pthread_t> *tids)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, Mastercode, (void *)"Master");
    if (n == 0)
    {
        std::cout << "create master success" << std::endl;
        tids->push_back(tid);
    }
}
void StartSlavers(std::vector<pthread_t> *tids, int num)
{
    for (int i = 1; i <= num; i++)
    {
        pthread_t tid;
        char *name = new char[64];
        snprintf(name, 64, "slaver-%d", i);
        int n = pthread_create(&tid, nullptr, Slavercode, (void *)name);
        if (n == 0)
        {
            std::cout << "create " << name << std::endl;
            tids->push_back(tid);
        }
    }
}
void WaitAll(std::vector<pthread_t> &tids)
{
    for (auto &e : tids)
    {
        pthread_join(e, nullptr);
    }
}
int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlavers(&tids, 5);
    WaitAll(tids);

    return 0;
}